package com.laguille.games.monopoly.server;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.commons.lang.Validate;

import com.laguille.games.monopoly.commons.event.Event;
import com.laguille.games.monopoly.commons.player.Player;

public class EventBusImpl implements EventBus {

	private final Map<Player, LinkedBlockingQueue<Event>> mapPlayerQueue;
	
	protected EventBusImpl() {
		mapPlayerQueue = new HashMap<Player, LinkedBlockingQueue<Event>>(10);
	}
	
	@Override
	public void registerPlayer(Player player) {
		Validate.notNull(player);
		Validate.isTrue(!mapPlayerQueue.containsKey(player));
		
		mapPlayerQueue.put(player, new LinkedBlockingQueue<Event>());
		
	}
	
	@Override
	public void unregisterPlayer(Player player) {
		mapPlayerQueue.remove(player);
	}
	
	@Override
	public void pushEvent(Event event, Player player) {
		Validate.notNull(event);
		Validate.notNull(player);
		Validate.isTrue(mapPlayerQueue.containsKey(player));
				
		LinkedBlockingQueue<Event> eventQueue = mapPlayerQueue.get(player);
		eventQueue.add(event);
	}

	@Override
	public void pushUniversalEvent(Event event) {
		Validate.notNull(event);

		if (mapPlayerQueue.isEmpty()) {
			throw new IllegalStateException("Event pushed but no players registered, event = " + event.toString());
		}
		
		for (LinkedBlockingQueue<Event> eventQueue : mapPlayerQueue.values()) {
			eventQueue.add(event);
		}
	}

	@Override
	public Event pullEvent(Player player) throws InterruptedException {
		Validate.notNull(player);
		Validate.isTrue(mapPlayerQueue.containsKey(player));
		
		LinkedBlockingQueue<Event> eventQueue = mapPlayerQueue.get(player);
		return eventQueue.take();
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "EventBusImpl [mapPlayerQueue=" + mapPlayerQueue + "]";
	}

	private static EventBus instance;
	public static EventBus getInstance() {
		if (instance == null) {
			instance = new EventBusImpl();
		}
		return instance;
	}
}
